package thread_design;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/5/25
 * Time:20:39
 * 懒汉方式v1-不安全
 **/
public class Demo3 {
    static class Singleton {
        //1.先创建一个私有的构造函数,防止其他类直接实例化
        private Singleton(){

        }
        //2.创建私有的类对象
        private static Singleton singleton = null;

        //3.提供统一的访问方法
        public static Singleton getInstance() {
            if(singleton==null) {//第一次访问
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                singleton = new Singleton();
            }
            return singleton;
        }
    }

    private static Singleton s1 = null;
    private static Singleton s2 = null;

    public static void main(String[] args) throws InterruptedException {
        //创建新线程执行任务
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                s1 = Singleton.getInstance();
            }
        });
        t1.start();

        //使用主线程执行任务
        s2 = Singleton.getInstance();

        t1.join();

        System.out.println(s1==s2);
    }

}
